package boot.spring.controller;

import boot.spring.po.Admin;
import boot.spring.po.Staff;
import boot.spring.service.AdminService;
import boot.spring.service.WebSocketServer;
import boot.spring.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import com.alibaba.fastjson.JSON;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.ArrayList;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    LoginService loginService;

    @GetMapping("/login")
    public String loginPage() {
        return "admin_login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        Model model) {
        Admin admin = adminService.getAdminByUsername(username);
        if (admin == null || !admin.getPassword().equals(password)) {
            model.addAttribute("errorMsg", "账号或密码错误");
            return "admin_login";
        }
        session.setAttribute("admin", admin);
        return "redirect:/admin/dashboard";
    }

    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return "redirect:/admin/login";
        List<Staff> users = adminService.getAllUsers();
        model.addAttribute("admin", admin);
        model.addAttribute("users", users);
        return "admin_dashboard";
    }

    @PostMapping("/deleteUser")
    @ResponseBody
    public String deleteUser(@RequestParam("id") int id, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return "未登录";
        String username = loginService.getnamebyid(id);
        adminService.deleteUserByIdAndForceLogout(id, username);
        return "success";
    }

    @PostMapping("/notice")
    @ResponseBody
    public String sendNotice(@RequestParam("content") String content, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return "未登录";
        adminService.insertNotice(content);
        // WebSocket广播所有在线用户，发送完整消息对象，增加type字段
        HashMap<String, Object> msg = new HashMap<>();
        msg.put("from", "[系统通知]");
        msg.put("type", "notice");
        msg.put("text", content);
        msg.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        msg.put("to", -1);
        webSocketServer.broadcast(JSON.toJSONString(msg));
        return "success";
    }

    @GetMapping("/users")
    @ResponseBody
    public List<Staff> getUsers(@RequestParam(value = "search", required = false) String search,
                                @RequestParam(value = "page", defaultValue = "1") int page,
                                @RequestParam(value = "size", defaultValue = "20") int size) {
        int offset = (page - 1) * size;
        List<Staff> users = adminService.getUsersBySearch(search, offset, size);
        // 设置在线状态
        java.util.Set<String> onlineUsers = WebSocketServer.getSessionPools().keySet();
        for (Staff user : users) {
            user.setActive(onlineUsers.contains(user.getUsername()) ? 1 : 0);
        }
        return users;
    }

    @PostMapping("/userStatus")
    @ResponseBody
    public List<Map<String, Object>> getUserStatus(@RequestBody List<Integer> ids) {
        List<Map<String, Object>> result = new ArrayList<>();
        java.util.Set<String> onlineUsers = WebSocketServer.getSessionPools().keySet();
        for (Integer id : ids) {
            Staff user = adminService.getUserById(id);
            Map<String, Object> map = new HashMap<>();
            map.put("staff_id", id);
            map.put("active", (user != null && onlineUsers.contains(user.getUsername())) ? 1 : 0);
            result.add(map);
        }
        return result;
    }

    @PostMapping("/forceLogout")
    @ResponseBody
    public String forceLogout(@RequestParam("username") String username, HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) return "未登录";
        WebSocketServer.forceLogout(username);
        return "success";
    }
} 